import React, {useEffect, useRef, useState} from 'react';
import {Button, Card, Col, Form, Input, message, Modal, Row, Select, Space, Table, Tag, Tooltip, Upload} from "antd";
import {DeleteOutlined, AuditOutlined, EditOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import classes from "../../UserHandle/UserTable/index.module.scss";
import axios from "axios";
import {debounce} from "lodash";
import {
    reqAddNewAdmin,
    reqGetAdminList,
    reqDeleteAdmin,
    reqDeleteAdminList,
    reqUpdateAdmin
} from "../../../../api/backStage/role";

//添加用户表单的配置
const formItemLayout = {
    labelCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 8,
        },
    },
    wrapperCol: {
        xs: {
            span: 24,
        },
        sm: {
            span: 16,
        },
    },
};


//上传头像的方法
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    console.log(reader)
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
};


const CharacterManage = () => {

    const [adminListData, setAdminListData] = useState([])
    const [adminRoleData, setRoleData] = useState([])

    const [roleListData, setRoleListData] = useState([])
    const [form] = Form.useForm();

    const [editAdmin, setEditAdmin] = useState(false);
    const adminFormRef = useRef()

    const {Option} = Select;
    //批量删除
    const [adminSelectedRows, setAdminSelectedRows] = useState([])
    const [adminSelectedRowKeys, setAdminSelectedRowKeys] = useState([])
    const [deleteModalText, setDeleteModalText] = useState('删除之后不可恢复!');
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const [adminId, setAdminId] = useState(null);

    //新增用户的拟态框
    const [modalOpen, setModalOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);

    //上传头像
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState([]);

    useEffect(() => {
        getAdminData()
    }, [])

    useEffect(() => {
        if (editAdmin) {
            form.setFieldsValue({
                avatar: imageUrl
            })
        }
    }, [imageUrl])

    const getAdminData = async () => {
        const result = await reqGetAdminList()
        setAdminListData(result.data)
        setRoleData(result.rolesResult[0].children)
    }

    // useEffect(() => {
    //     getRoleData()
    // }, [])
    // const getRoleData = async () => {
    //     const result = await reqGetRoleList()
    //     setRoleListData(result.data)
    // }


    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            width: 70
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '职位',
            dataIndex: 'job',
            key: 'job',
            width: 500
        },
        {
            title: '权限',
            dataIndex: 'role',
            key: 'role',
            width: 500
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            render: (_, record) => (
                <Space size="middle">
                    <Button onClick={() => updateAdmin(record)} type="primary" style={{backgroundColor: '#ffa500'}}>
                        <Tooltip title="修改">
                            <EditOutlined/>
                        </Tooltip>
                    </Button>
                    <Button onClick={() => {
                        setAdminId(record.id)
                        setDeleteModalOpen(true)
                    }} type="primary" danger>
                        <Tooltip title="删除">
                            <DeleteOutlined/>
                        </Tooltip>
                    </Button>
                    <Button type="primary">
                        <Tooltip title="分配权限">
                            <AuditOutlined/>
                        </Tooltip>
                    </Button>
                </Space>
            ),
        },
    ];


    /*
    *       添加用户的事件
            添加用户表单
    *
    * */
    const addNewAdmin = () => {
        form.resetFields()
        setImageUrl(null)
        setEditAdmin(false)
        setModalOpen(true)
    }
    //添加管理员、修改管理员成功的事件
    const addAndUpdateHandleOk = async (fd) => {
        if (editAdmin) {
            try {
                const fd = form.getFieldValue()
                setConfirmLoading(true);
                const result = await reqUpdateAdmin({admin_id: fd.id, fd})
                if (result.status === 0) {
                    setTimeout(async () => {
                        setModalOpen(false);
                        setConfirmLoading(false);
                        message.success('修改管理员成功')
                        // getUserListData()
                        getAdminData()
                    }, 1000);
                } else {
                    message.error('修改失败')
                }
            } catch (err) {
                message.error(err)
            }
        } else {
            try {
                setConfirmLoading(true);
                const result = await reqAddNewAdmin({...fd, avatar: fd.avatar[0]})
                if (result.status === 0) {
                    setTimeout(async () => {
                        setModalOpen(false);
                        setConfirmLoading(false);
                        message.success('添加管理员成功')
                        // getUserListData()
                        getAdminData()
                    }, 1000);
                } else {
                    message.error('添加管理员失败')
                }
            } catch (err) {
                message.error(err)
            }
        }
    }
    const addHandleCancel = () => {
        setImageUrl(null)
        setModalOpen(false);
    };

    //自定义上传
    const customRequest = async (options) => {
        // console.log(options)
        const {onSuccess, onError, file} = options;
        const fmData = new FormData()
        const config = {
            headers: {"content-type": "multipart/form-data"},
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${process.env.REACT_APP_API_URL}/admin/manage/uploads`,
                fmData,
                config
            );
            const {url} = res.data;
            const fileObj = {
                uid: res.data.id,
                name: file.name,
                status: "done",
                url,
            };
            onSuccess(fileObj);
            console.log("server res: ", res);
        } catch (err) {
            console.log("Error: ", err);
            onError(err);
        }
    }
    //上传组件选择图片的事件
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            console.log(info)
            getBase64(info.file.originFileObj, (url) => {
                setLoading(false);
                setImageUrl([url]);
            });
        }
    };
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList
    }
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8,}}></div>
        </div>
    )

//重置添加用户表单

    const reset = () => {
        adminFormRef.current.resetFields()
    }


    //批量删除成功的操作
    const deleteOk = async () => {
        if (adminId) {
            const result = await reqDeleteAdmin({admin_id: adminId})
            if (result.status === 0) {
                setConfirmLoading(true);
                setTimeout(() => {
                    setDeleteModalOpen(false);
                    setConfirmLoading(false);
                    getAdminData()
                    message.success('删除成功!')
                }, 1000);
            }
        } else if (adminSelectedRowKeys) {
            const idList = []
            adminSelectedRowKeys.forEach((id) => {
                idList.push(id)
            })
            const result = await reqDeleteAdminList(idList)
            if (result.status === 0) {
                setConfirmLoading(true);
                setTimeout(() => {
                    setDeleteModalOpen(false);
                    setConfirmLoading(false);
                    getAdminData()
                    message.success('删除成功')
                }, 1000);
            }
        }


    }
    const deleteCancel = () => {
        setDeleteModalOpen(false)
    }

    //表格的选择框属性
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            setAdminSelectedRows(selectedRows)
            setAdminSelectedRowKeys(selectedRowKeys)
        },
        onSelect: (record, selected, selectedRows) => {
            setAdminSelectedRows(selectedRows)
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
            setAdminSelectedRows(selectedRows)
        },
    };


    const tableColumns = columns.map((item) => ({
        ...item,
    }));


    //更新用户
    const updateAdmin = (record) => {
        try {
            setEditAdmin(true)
            setModalOpen(true)
            setImageUrl([record.avatar])
            if (form) {
                form.setFieldsValue({
                    ...record,
                    avatar: imageUrl
                })
            }
        } catch (err) {
            message.error(err)
        }
    }


//用户角色筛选
    const chooseAdmin = async (role) => {
        console.log(role)
        const result = await reqGetAdminList()
        setAdminListData(result.data.filter((item) => item.role.indexOf(role) !== -1))
    }

//重置表格
    const searchFormRef = useRef()
    const resetAdminList = () => {
        getAdminData()
        searchFormRef.current.resetFields()
    }
    //搜索用户
    const searchAdmin = debounce(async (e) => {
        const result = await reqGetAdminList()
        setAdminListData(result.data.filter((item) => item.name.indexOf(e.target.value) !== -1))
    }, 500)


    //密码校验
    const validatePassword = (_, value) => {
        if (!value) {
            return Promise.reject('请输入密码!');
        }
        if (value.length < 6) {
            return Promise.reject('密码长度至少是6位!');
        }
        return Promise.resolve();
    };

    //确认密码校验
    const validateConfirmPassword = (_, value) => {
        if (!value) {
            return Promise.reject('请确认密码!');
        }
        if (value !== form.getFieldValue('password')) {
            return Promise.reject('两次密码输入必须一致!');
        }
        return Promise.resolve();
    };


    return (
        <div>
            <Card>
                <div style={{display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between'}}>
                    <Space>
                        <Button onClick={addNewAdmin} type="primary">新增角色</Button>
                        <Button type="primary" onClick={() => {
                            if (adminSelectedRows.length !== 0) {
                                setDeleteModalOpen(true)
                            } else {
                                message.info('请勾选用户')
                            }
                        }} danger>批量删除</Button>
                    </Space>
                    <Form ref={searchFormRef} style={{display: 'flex'}}>
                        <Space>
                            <Form.Item name="select">
                                <Select
                                    placeholder="全部"
                                    style={{width: 120}}
                                    allowClear
                                    onChange={chooseAdmin}
                                    options={[
                                        {
                                            value: '超级管理员',
                                            label: '超级管理员',
                                        }, {
                                            value: '普通管理员',
                                            label: '普通管理员',
                                        },
                                    ]}
                                />
                            </Form.Item>
                            <Form.Item name="search">
                                <Input.Search placeholder="根据名称搜索" onChange={searchAdmin} />
                            </Form.Item>
                            <Form.Item>
                                <Button onClick={() => resetAdminList()} >重置</Button>
                            </Form.Item>
                        </Space>
                    </Form>
                </div>

                <Table
                    bordered
                    columns={columns}
                    // expandable={{
                    // expandedRowRender: (record) => (
                    //     adminRoleData.map((item) => (
                    //         <div style={{borderTop: '1px solid #eee'}}>
                    //             <Row style={{height: 100}} key={item.id}>
                    //                 <Col style={{display: 'flex', alignItems: 'center'}} span={4}>
                    //                     <Tag style={{fontSize: 14}} color="#2db7f5" closable>
                    //                         {item.authName}
                    //                     </Tag>
                    //                     <CaretRightOutlined/>
                    //                 </Col>
                    //                 <Col style={{
                    //                     display: 'flex',
                    //                     justifyContent: 'space-around',
                    //                     flexDirection: 'column'
                    //                 }} span={20}>
                    //                     {
                    //                         item.children.map((item) => (
                    //                             <Space>
                    //                                 <Row gutter={100} key={item.id}>
                    //                                     <Col style={{display: 'flex', alignItems: 'center'}}>
                    //                                         <Tag style={{fontSize: 14}} color="#87d068" closable>
                    //                                             {item.authName}
                    //                                         </Tag>
                    //                                         <CaretRightOutlined/>
                    //                                     </Col>
                    //                                     <Col span={8}
                    //                                          style={{display: 'flex', alignItems: 'center'}}>
                    //                                         {
                    //                                             item.children.map((item) => (
                    //                                                 <Space>
                    //                                                     <Row key={item.id}>
                    //                                                         <Col style={{
                    //                                                             display: 'flex',
                    //                                                             alignItems: 'center'
                    //                                                         }}>
                    //                                                             <Tag style={{fontSize: 14}}
                    //                                                                  color="orange" closable>
                    //                                                                 {item.authName}
                    //                                                             </Tag>
                    //                                                         </Col>
                    //                                                     </Row>
                    //                                                 </Space>
                    //                                             ))
                    //                                         }
                    //                                     </Col>
                    //                                 </Row>
                    //                             </Space>
                    //                         ))
                    //                     }
                    //                 </Col>
                    //
                    //             </Row>
                    //         </div>
                    //     ))
                    // )
                    // rowExpandable: (record) => record.name !== 'Not Expandable',
                    //}}
                    rowSelection={{...rowSelection}}
                    dataSource={adminListData}
                    rowKey={record => record.id}
                />
            </Card>
            <Modal
                width={800}
                title={editAdmin ? "编辑管理员" : "新增管理员"}
                open={modalOpen}
                onCancel={addHandleCancel}
                footer={null}
            >
                <Form
                    {...formItemLayout}
                    ref={adminFormRef}
                    form={form}
                    name="add"
                    onFinish={addAndUpdateHandleOk}
                    style={{maxWidth: 600}}
                    scrollToFirstError
                >
                    <Form.Item
                        name="name"
                        label="名称"
                        rules={[
                            {
                                required: true,
                                message: '请输入名称!',
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        name="phone"
                        label="手机号"
                        rules={[
                            {
                                type: 'phone',
                                message: '手机号不符合规范!',
                            },
                            {
                                required: true,
                                message: '请输入手机号!',
                            },
                        ]}
                    >
                        <Input maxLength={13}/>
                    </Form.Item>

                    <Form.Item
                        name="role"
                        label="分配权限"
                        rules={[
                            {
                                required: true,
                                message: '请分配权限!',
                            },
                        ]}
                    >
                        <Select placeholder="分配该用户权限">
                            <Option value="超级管理员">超级管理员</Option>
                            <Option value="普通管理员">普通管理员</Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="job"
                        label="职务"
                        rules={[
                            {
                                required: true,
                                message: '请输入职务!',
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[{validator: validatePassword}]}
                        hasFeedback
                    >
                        <Input.Password/>
                    </Form.Item>

                    {
                        editAdmin ? null :
                            <Form.Item
                                name="confirm"
                                label="确认密码"
                                dependencies={['password']}
                                hasFeedback
                                rules={[{validator: validateConfirmPassword}]}
                            >
                                <Input.Password/>
                            </Form.Item>
                    }


                    <Form.Item
                        name="account"
                        label="账号名"
                        tooltip="你期望取一个什么账号名?"
                        rules={[
                            {
                                required: true,
                                message: '请输入账号名!',
                                whitespace: true,
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>


                    <Form.Item
                        name="avatar"
                        label="上传头像"
                        rules={[
                            {
                                required: true,
                                message: '请上传头像!',
                            },
                        ]}
                        getValueFromEvent={normFile}
                        valuePropName="fileList">

                        <Upload
                            listType="picture-card"
                            showUploadList={false}
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                            maxCount={1}
                            customRequest={customRequest}
                        >
                            {imageUrl ? (
                                <img
                                    src={imageUrl}
                                    alt="avatar"
                                    style={{width: '100%'}}
                                />
                            ) : (uploadButton)}
                        </Upload>
                    </Form.Item>

                    <Form.Item
                        name="signature"
                        label="签名"
                        rules={[
                            {
                                required: true,
                                message: '请输入签名!',
                                whitespace: true,
                            },
                        ]}
                    >
                        <Input/>
                    </Form.Item>


                    <div className={classes.FooterBtn}>
                        <div>
                            <Form.Item>
                                <Button onClick={reset} type="primary">
                                    重置表单
                                </Button>
                            </Form.Item>
                        </div>
                        <div style={{display: 'flex'}}>
                            <Space>
                                <Form.Item>
                                    <Button onClick={() => {
                                        setConfirmLoading(false)
                                        setModalOpen(false)
                                    }}>
                                        取消
                                    </Button>
                                </Form.Item>
                                <Form.Item>
                                    <Button type="primary" htmlType="submit" loading={confirmLoading}>
                                        {editAdmin ? "确认修改" : "确认添加"}
                                    </Button>
                                </Form.Item>
                            </Space>
                        </div>
                    </div>
                </Form>
            </Modal>
            <Modal
                centered
                title="确定要删除所选项吗？"
                open={deleteModalOpen}
                onOk={deleteOk}
                confirmLoading={confirmLoading}
                onCancel={deleteCancel}
                okText="确认删除"
                cancelText="取消"
            >
                <p>{deleteModalText}</p>
            </Modal>
        </div>
    )
};

export default CharacterManage;